package com.wen.update;

import android.app.IntentService;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.webkit.URLUtil;

import com.wen.fileprovider.FileProvider7;
import com.wen.update.listener.OnUpdateListener;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 更新APK的服务
 */

public class UpdateService extends IntentService {
    public static final String SERVICE_ACTION = "wen.update.service";
    /**
     * 失败
     */
    public static final int UPDATE_FAILED = 1;
    /**
     * 进度
     */
    public static final int UPDATE_PROGRESS = 2;
    /**
     * 成功
     */
    public static final int UPDATE_SUCCEED = 3;
    /**
     * apk下载的URL
     */
    public static final String APK_URL = "APK_URL";
    public static final String VERSION_NAME = "versionName";
    public static final String APK_NAME = "acxw.apk";
    private String mApkUrl;
    public static OnUpdateListener mUpdateListener;
    public static boolean isLoading = false;
    /**
     * 通知样管理类
     */
    private NotifyManager mNotifyManager;


    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg == null) {
                return;
            }
            Update update = (Update) msg.obj;
            if (mUpdateListener == null || update == null) {
                return;
            }
            switch (msg.what) {
                case UPDATE_FAILED:
                    mUpdateListener.onFailed(update.msg);
                    break;
                case UPDATE_PROGRESS:
                    mUpdateListener.onProgress(update.total, update.current, update.progress);
                    break;
                case UPDATE_SUCCEED:
                    mUpdateListener.onSucceed(update.apkFile);
                    break;
            }
        }


    };


    public UpdateService() {
        super("UpdateService");
    }

    @Override
    public void onDestroy() {
        // 移除通知
        if (mNotifyManager != null) {
            mNotifyManager.cancel();
        }
        mUpdateListener = null;
        mNotifyManager = null;
        super.onDestroy();
    }


    /**
     * 这个方法可以做耗时的操作
     */
    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

        if (intent == null) {
            return;
        }
        String action = intent.getAction();
        if (!SERVICE_ACTION.equals(action)) {
            return;
        }
        if (isLoading) {
            return;
        }
        isLoading = true;
        mApkUrl = intent.getStringExtra(APK_URL);
        String versionName = intent.getStringExtra(VERSION_NAME);
        Update update = new Update();
        try {
            if (!URLUtil.isNetworkUrl(mApkUrl)) {
                update.msg = "APK下载地址不正确";
                // 更新失败
                sendUpdate(UPDATE_FAILED, update);
                return;
            }
            // 1. 初始化通知栏
            mNotifyManager = new NotifyManager(this, versionName);
            // 2. 打开网络去下载
            URL url = new URL(mApkUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            int total = connection.getContentLength();
            int current = 0;
            InputStream is = connection.getInputStream();
            // 3. 将下载好的APK写入SD卡
            File apkFile = createApkFile();
            FileOutputStream fos = new FileOutputStream(apkFile);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024 * 1024];
            int len = -1;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                current += len;
                // 4. 更新进度
                float progress = current * 100f / total;
                update.current = current;
                update.total = total;
                update.progress = progress;
                sendUpdate(UPDATE_PROGRESS, update);
                mNotifyManager.updateProgress((int) progress);
            }
            update.apkFile = apkFile;
            // 5.下载成功
            sendUpdate(UPDATE_SUCCEED, update);
            // 移除通知
            mNotifyManager.cancel();
            FileProvider7.installApk(this, apkFile);
        } catch (Exception e) {
            e.printStackTrace();
            update.msg = "下载APK失败";
            // 更新失败
            sendUpdate(UPDATE_FAILED, update);
        }
        isLoading = false;
    }


    /**
     * 发送消息
     */
    private void sendUpdate(int what, Update update) {
        Message obtain = Message.obtain();
        obtain.obj = update;
        obtain.what = what;
        mHandler.sendMessage(obtain);
    }

    private static class Update {
        String msg;
        int total;
        int current;
        float progress;
        File apkFile;
    }

    /**
     * 创建apk下载文件
     */
    public File createApkFile() {
        // 创建目录
        File directory = null;
        if (checkSDExist()) {
            directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        }
        if (directory == null) {
            directory = getCacheDir();
        }
        if (!directory.exists()) {
            directory.mkdirs();
        }
        File apkFile = new File(directory, APK_NAME);
        if (apkFile != null && !apkFile.exists()) {
            try {
                apkFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return apkFile;
    }

    // 检查是否SDK准备好
    public boolean checkSDExist() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

}
